package com.tusuo.stds.ui.scenedetail;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.tusuo.stds.R;
import com.tusuo.stds.rest.SceneDetail;
import com.tusuo.stds.rest.SceneList;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.pay.MyPayActivity_;
import com.tusuo.stds.ui.reward.RewardActivity_;
import com.tusuo.stds.ui.scene.SceneActivity;
import com.tusuo.stds.ui.scene.SceneActivity_;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.parceler.Parcels;

import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

@EActivity(R.layout.activity_scene_detail)
public class SceneDetailActivity extends BaseToolbarActivity<SceneDetailView,SceneDetailPresenter> implements SceneDetailView{

    @ViewById(R.id.scene_detail_btn_can)
    Button canBtn;
    @ViewById(R.id.scene_detail_btn_depend)
    Button dependBtn;
    @ViewById(R.id.scene_detail_btn_reward)
    Button rewardBtn;

    @ViewById(R.id.scene_detail_layout_reward)
    LinearLayout layoutReward;

    @ViewById(R.id.scene_detail_civ_icon)
    CircleImageView iconImage;
    @ViewById(R.id.scene_detail_iv_background)
    ImageView backgroundImage;

    @ViewById(R.id.scene_detail_tv_no_network)
    TextView tvNoNetwork;
    @ViewById(R.id.scene_detail_layout_scroll_view)
    ScrollView layoutScrollView;

    @ViewById(R.id.scene_detail_tv_name)
    TextView nameText;
    @ViewById(R.id.scene_detail_tv_join_num)
    TextView joinNumText;
    @ViewById(R.id.scene_detail_tv_license)
    TextView licenseText;
    @ViewById(R.id.scene_detail_tv_reward_num)
    TextView rewardNumText;
    @ViewById(R.id.scene_detail_tv_description)
    TextView descriptionText;
    @ViewById(R.id.scene_detail_tv_price_description)
    TextView priceDescriptionText;
    @ViewById(R.id.scene_detail_tv_price)
    TextView priceText;
    @ViewById(R.id.scene_detail_tv_depend_description)
    TextView dependDescriptionText;

    @ViewById(R.id.scene_detail_layout_level_list)
    LinearLayout levelListLayout;
    @ViewById(R.id.scene_detail_layout_reward_num)
    LinearLayout layoutRewardNum;
    @ViewById(R.id.scene_detail_layout_reward_list)
    LinearLayout rewardListLayout;
    @ViewById(R.id.scene_detail_layout_price)
    LinearLayout priceLayout;
    @ViewById(R.id.scene_detail_layout_depend)
    LinearLayout dependLayout;

    @ColorRes(R.color.transparent)
    int toolbarBgColor;
    @ColorRes(R.color.white)
    int toolbarTextColor;

    private int sceneId;
    private String title;
    private float price;
    private NormalDialog mDialog;
    private SceneDetail sceneDetail;
    private SceneList.Scene mScene;
    private SceneList.Scene dependScene;

    private boolean mFromSelf = false;  // 此Activity由于业务流程原因不使用SingleTask，故设立该flag完成类似现象

    @NonNull
    @Override
    public SceneDetailPresenter createPresenter() {
        return new SceneDetailPresenter(this);
    }

    @AfterInject
    void init() {
        mScene = Parcels.unwrap(getIntent().getParcelableExtra(SceneList.Scene.EXTRA_NAME));
        sceneId = getIntent().getIntExtra("sceneId",-1);
        if (sceneId == -1) {
            sceneId = mScene.Id;
        }

        mFromSelf = getIntent().getBooleanExtra(SceneActivity.FROM_SELF, false);
    }

    @AfterViews
    public void initData() {
        setupUI(this);
        ToolbarOwner.Config config = new ToolbarOwner.Config("场景详情", true, null);
        mToolbarOwner.setConfig(config);
    }

    @Override
    protected void onResume() {
        super.onResume();

        tvNoNetwork.setVisibility(View.VISIBLE);
        layoutScrollView.setVisibility(View.GONE);

        if (sceneId > 0) {
            presenter.initData(sceneId);
        }
    }

    @Override
    protected void onDestroy() {
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }
        super.onDestroy();
    }

    @Override
    public void initAllView(SceneDetail sceneDetail) {
        this.sceneDetail = sceneDetail;
        title = sceneDetail.Title;

        mScene.Title = title;
        mScene.CompleteType = 1;

        setupUI(this, toolbarBgColor, toolbarTextColor);
        ToolbarOwner.Config config = new ToolbarOwner.Config(title, true, R.drawable.ic_back_light, null);
        mToolbarOwner.setConfig(config);

        tvNoNetwork.setVisibility(View.GONE);
        layoutScrollView.setVisibility(View.VISIBLE);

        String licenseName = "";
        if (sceneDetail.LicenseId != 0) {
            licenseName = sceneDetail.LicenseName;
        }

        if (TextUtils.isEmpty(licenseName)) {
            licenseName = "";
        }

        if (!TextUtils.isEmpty(sceneDetail.LicenseLogo)) {
            Glide
                    .with(this)
                    .load(Utils.getCorrectImageUrl(sceneDetail.LicenseLogo))
                    .error(R.drawable.img_avatar_default)
                    .centerCrop()
                    .crossFade()
                    .skipMemoryCache(true)  // 不加入到内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)  // 缓存图片源文件
                    .into(iconImage);
        }else {
            iconImage.setImageResource(R.drawable.img_avatar_default);
        }

        if (TextUtils.isEmpty(sceneDetail.DependDescription)) {
            dependLayout.setVisibility(View.GONE);
        }else {
            dependLayout.setVisibility(View.VISIBLE);
            dependDescriptionText.setText(sceneDetail.DependDescription);
        }

        int windowWidth = getWindowManager().getDefaultDisplay().getWidth();

        Glide
                .with(this)
                .load(Utils.getCorrectImageUrl(sceneDetail.ImageUrl))
                .crossFade()
                .into(backgroundImage);

        descriptionText.setText(sceneDetail.Description);

        joinNumText.setText(sceneDetail.JoinCount+"");

        nameText.setText(licenseName);

        // 锁定状态
        if (sceneDetail.LockStatus == 0) {
            if (sceneDetail.IsDependFinish) {
                // 需要付费
                canBtn.setVisibility(View.GONE);
                dependBtn.setVisibility(View.GONE);
                priceLayout.setVisibility(View.VISIBLE);
            }else {
                // 依赖不是空　需要依赖
                canBtn.setVisibility(View.GONE);
                dependBtn.setVisibility(View.VISIBLE);
                priceLayout.setVisibility(View.GONE);
            }
            layoutReward.setVisibility(View.GONE);
        }else if (sceneDetail.LockStatus == 10) {
            // 未锁定状态
            canBtn.setVisibility(View.VISIBLE);
            dependBtn.setVisibility(View.GONE);
            priceLayout.setVisibility(View.GONE);
        }

        price = sceneDetail.Price;

        priceText.setText(price + "");

        if (TextUtils.isEmpty(sceneDetail.PriceDescription)) {
            priceDescriptionText.setVisibility(View.GONE);
        }else {
            priceDescriptionText.setText(sceneDetail.PriceDescription);
            priceDescriptionText.setVisibility(View.VISIBLE);
        }

        List<SceneDetail.SceneModule> sceneModuleList = sceneDetail.SceneModuleList;
        LinearLayout.LayoutParams levelParams =  new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        int padding = (int) getResources().getDimension(R.dimen.module_padding);

        // 清空刷新前的数据
        levelListLayout.removeAllViews();

        if (sceneModuleList != null) {
            for (final SceneDetail.SceneModule module : sceneModuleList) {
                TextView tvItem = new TextView(this);
                levelParams.setMargins(0,11,0,11);
                tvItem.setText(module.Title);
                tvItem.setTextColor(Color.WHITE);
                tvItem.setTextSize(17);
                tvItem.setBackground(getResources().getDrawable(R.drawable.shape_theme_button_normal));
                tvItem.setPadding(padding,padding,padding,padding);
                tvItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(SceneDetailActivity.this,ModuleDetailActivity.class);
                        intent.putExtra("module", Parcels.wrap(module));
                        startActivity(intent);
                    }
                });
                levelListLayout.addView(tvItem,levelParams);
            }
        }

        if (sceneDetail.RewardCount > 0) {
            layoutRewardNum.setVisibility(View.VISIBLE);
            rewardNumText.setText(sceneDetail.RewardCount + "");
        } else {
            layoutRewardNum.setVisibility(View.GONE);
        }

        // 清空刷新前的数据
        rewardListLayout.removeAllViews();

        List<SceneDetail.Reward> rewardList = sceneDetail.RewardList;
        LinearLayout.LayoutParams rewardParams = new LinearLayout.LayoutParams(windowWidth / 10,windowWidth / 10);
        if (rewardList != null) {
            int num;
            if (rewardList.size() <= 8) {
                num = rewardList.size();
            }else {
                num = 8;
            }

            for (int i = 0; i < num; i ++) {
                final CircleImageView civItem = new CircleImageView(SceneDetailActivity.this);
                rewardParams.setMargins(5,5,5,5);
                String imageUrl = rewardList.get(i).ImageUrl;

                if (TextUtils.isEmpty(imageUrl)) {
                    civItem.setImageResource(R.drawable.img_avatar_default);
                } else {
                    Glide
                            .with(SceneDetailActivity.this)
                            .load(Utils.getCorrectImageUrl(imageUrl))
                            .asBitmap()
                            .centerCrop()
                            .error(R.drawable.img_avatar_default)
                            .skipMemoryCache(true)  // 不加入到内存缓存
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)  // 缓存图片源文件
                            .override(windowWidth / 10, windowWidth / 10)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                    civItem.setImageBitmap(resource);
                                }
                            });
                }

                rewardListLayout.addView(civItem, rewardParams);
            }
        }
        initDialog();

        licenseText.setText(sceneDetail.LicenseName);
    }

    @Override
    public void initDependScene(List<SceneList.Scene> data, int sceneId) {
        for (SceneList.Scene scene : data) {
            if (scene.Id == sceneId) {
                dependScene = scene;
            }
        }
    }

    public void initDialog() {
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();
        mDialog = new NormalDialog(this);
        mDialog.isTitleShow(false)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(sceneDetail.DependDescription)
                .contentGravity(Gravity.CENTER)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("我知道了", "前往")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#333333"), Color.parseColor("#333333"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        mDialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                        Intent intent = new Intent(SceneDetailActivity.this,SceneDetailActivity_.class);
                        intent.putExtra("sceneId",sceneDetail.DependId);
                        intent.putExtra(SceneList.Scene.EXTRA_NAME, Parcels.wrap(dependScene));
                        startActivity(intent);
                    }
                }
        );

    }

    /**
     * 该场景免费，可以直接跳转到闯关
     */
    @Click(R.id.scene_detail_btn_can)
    public void goToFreeScene() {
        Intent intent = new Intent(this, SceneActivity_.class);
        intent.putExtra(SceneList.Scene.EXTRA_NAME, Parcels.wrap(mScene));
        startActivity(intent);
    }

    /**
     * 该场景需要付费，点击跳转到支付的界面
     */
    @Click(R.id.scene_detail_layout_price)
    public void payForUnlockScene() {
        Intent intent = new Intent(this, MyPayActivity_.class);
        intent.putExtra("payType","unlock");
        intent.putExtra("sceneTitle",title);
        intent.putExtra("scenePrice",price);
        intent.putExtra("sceneId",sceneId);
        startActivity(intent);
    }

    /**
     * 该场景需要依赖，点击跳转依赖场景详情页面
     */
    @Click(R.id.scene_detail_btn_depend)
    public void showDependDialog() {
        mDialog.show();
    }

    /**
     * 打赏该场景
     */
    @Click(R.id.scene_detail_btn_reward)
    public void rewardScene() {
        Intent intent = new Intent(this, RewardActivity_.class);
        intent.putExtra("sceneTitle",title);
        intent.putExtra("sceneId",sceneId);
        startActivity(intent);
    }
}
